<script>
  import { onMount } from 'svelte';
  export let options = [];
  export let selected = '';
  export let onSelect = () => {};
  
  let isOpen = false;
  let dropdownRef;

  function handleClick(option) {
    selected = option;
    onSelect(option);
    isOpen = !isOpen;
  }

  onMount(() => {
    window.addEventListener('click', handleOutsideClick);
    return () => {
      window.removeEventListener('click', handleOutsideClick);
    };
  });

  function handleOutsideClick(event) {
    if (!dropdownRef.contains(event.target)) {
      isOpen = false;
    }
  }
</script>

<div class="dropdown-list" bind:this={dropdownRef} on:click={() => isOpen = !isOpen}>
  <div class="selected-option">
    <h5>{selected}</h5>
    {#if isOpen}
      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none" style="pointer-events: none;">
        <path d="M8.00003 4C8.12791 4 8.25591 4.04882 8.35353 4.14645L13.3535 9.14645C13.5488 9.34182 13.5489 9.6582 13.3535 9.85345C13.1583 10.0488 12.8419 10.0488 12.6465 9.85345L8.00003 5.207L3.35353 9.85345C3.15828 10.0488 2.84191 10.0488 2.64653 9.85345C2.45116 9.65807 2.45116 9.3417 2.64653 9.14645L7.64653 4.14645C7.74416 4.04882 7.87216 4 8.00003 4Z" fill="#14031F"/>
      </svg>
    {:else}
      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none" style="pointer-events: none;">
        <path d="M8.00003 12C7.87216 12 7.74416 11.9512 7.64653 11.8535L2.64653 6.85353C2.45116 6.65816 2.45116 6.34178 2.64653 6.14653C2.84191 5.95128 3.15828 5.95116 3.35353 6.14653L8.00003 10.793L12.6465 6.14653C12.8419 5.95116 13.1583 5.95116 13.3535 6.14653C13.5488 6.34191 13.5489 6.65828 13.3535 6.85353L8.35353 11.8535C8.25591 11.9512 8.12791 12 8.00003 12Z" fill="#14031F"/>
      </svg>
    {/if}
  </div>
  {#if isOpen}
    <div class="options active">
      {#each options as option}
        <div class="dropdown-item" on:click={() => handleClick(option)}>{option}</div>
      {/each}
    </div>
  {/if}
</div>
